<template>
  <h1>详情页</h1>
  <hr>
  <div>
      <h1>{{weibo.nickname}}说了:{{weibo.content}}</h1>
      <p>发布于:{{weibo.created}}</p>
  </div>
  <div>
    <el-input v-model="comment.content" placeholder="注意友善评论哦!" ></el-input>
    <el-button type="primary" @click="insert()">发布</el-button>
  </div>
  <div v-for="c in commentList">
    <h4>{{c.nickname}}评论说:{{c.content}}</h4>
    <span>发布于:{{c.created}}</span>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import axios from "axios";
import router from "@/router";
import {ElMessage} from "element-plus";
import qs from "qs";



const weibo=ref({
  nickname:'',
  content:'',
  created:''
})

onMounted(()=>{
  //从url中获取请求参数
  let id=new URLSearchParams(location.search).get('id');
  loadComment();
  console.log('请求的id:'+id)
  axios.get('http://localhost:8080/v1/weibo/detail/'+id)
      .then((res)=>{
        if (res.data.code==2002){
          weibo.value=res.data.data;
        }
      })
})

const comment=ref({
  content:'',
});
let user=localStorage.user?JSON.parse(localStorage.user):null;
const insert=()=>{
  comment.value.weiboId=new URLSearchParams(location.search).get('id');

  console.log('存储的user对象'+user);
  if (user==null){
    ElMessage.warning('请登录');
    router.push('/reg');
    return;
  }
  comment.value.userId=user.id;
  console.log(comment.value);
  let data=qs.stringify(comment.value);
  axios.post('http://localhost:8080/v1/comment/insert',data)
        .then((res)=>{
          if (res.data.code==2002){
            ElMessage.success('发布成功');
            loadComment();
          }else {
            ElMessage.info('发布失败');
          }
        });

}


const  commentList=ref([]);
const loadComment=()=>{
  let weiboId=new URLSearchParams(location.search).get('id');
  console.log('微博id:'+weiboId)
  axios.get('http://localhost:8080/v1/comment/list/'+weiboId)
      .then((res)=>{
        if (user==null){
          ElMessage.error("请登录");
          router.push('/login');
          return;
        }
        if (res.data.code==2002){
          ElMessage.success("查询成功");
          commentList.value=res.data.data;
        }
      })
}
</script>

<style scoped>

</style>